from __future__ import print_function

import logging

from collections import deque
import os
import sys

import twitter

import getch

__author__ = 'rjs'

logger = logging.getLogger('twiterator.scheduler')

CONSUMER_KEY='uS6hO2sV6tDKIOeVjhnFnQ'
CONSUMER_SECRET='MEYTOS97VvlHX7K1rwHPEqVpTSqZ71HtvoK4sVuYk'

ESCAPE = 27
CONTROL_C = 3

def interactive(pending_tweets_filename, sent_tweets_filename=None, for_real=False):
    '''Read the tweets from pending_tweets_filename one by one, send them when
    requested, and store sent tweets in sent_tweetfile. Sent tweets will be
    removes from the pending_tweets_filename.

    Args:
        pending_tweets_filename: The path to a text file containing one tweet per line.
        send_tweets_filename: The path to a text file which will contain sent tweets.
    '''

    sent_tweets_filename = create_sent_tweets_filename(pending_tweets_filename, sent_tweets_filename)
    pending_tweets = read_pending_tweets(pending_tweets_filename)
    warn_on_long_tweets(pending_tweets)

    tweeter = create_tweeter() if for_real else None

    while len(pending_tweets) > 0:
        tweet = pending_tweets.popleft()
        sys.stderr.write('NEXT: "{0}"'.format(tweet.strip()))
        c = ord(getch.getch())
        if c == CONTROL_C or c == ESCAPE:
            return
        sys.stderr.write('\n')
        send_tweet(tweeter, tweet.strip())
        write_sent_tweet(sent_tweets_filename, tweet)
        write_pending_tweets(pending_tweets_filename, pending_tweets)


def create_sent_tweets_filename(pending_tweets_filename, sent_tweets_filename):
    if sent_tweets_filename is not None:
        return sent_tweets_filename
    body, ext = os.path.splitext(pending_tweets_filename)
    return "{0}.sent{1}".format(body, ext)


def read_pending_tweets(pending_tweets_filename):
    with open(pending_tweets_filename, 'r') as pending_tweets_file:
        return deque(line for line in pending_tweets_file.readlines() if len(line.strip()) > 0)


def warn_on_long_tweets(pending_tweets):
    for tweet in pending_tweets:
        if len(tweet) > 140:
            logger.warn('Tweet "{0}" is too long at {1} characters'.format(tweet, len(tweet)))


def create_tweeter():
    oauth_filename = os.path.expanduser(os.environ.get('HOME', '') + os.sep + '.twitter_oauth')
    oauth_token, oauth_token_secret = twitter.oauth.read_token_file(oauth_filename)
    t = twitter.api.Twitter(auth=twitter.oauth.OAuth(oauth_token, oauth_token_secret,
                                                     CONSUMER_KEY, CONSUMER_SECRET),
                                                     secure=True,
                                                     api_version='1',
                                                     domain='api.twitter.com')
    return t


def send_tweet(tweeter, tweet):
    if tweeter is not None:
        tweeter.statuses.update(status=tweet[0:140])
    logger.info("TWEET!")


def write_sent_tweet(sent_tweets_filename, tweet):
    with open(sent_tweets_filename, 'a') as sent_tweets_file:
        sent_tweets_file.write(tweet)


def write_pending_tweets(pending_tweets_filename, pending_tweets):
    with open(pending_tweets_filename, 'w') as pending_tweets_file:
        for pending_tweet in pending_tweets:
            pending_tweets_file.write(pending_tweet)
